package net.mimai.vultrue.bus.utils;

import net.mimai.vultrue.framework.base.context.FrameworkContextDataHolder;
import net.mimai.vultrue.framework.utils.FrameworkUtils;
import net.mimai.vultrue.framework.utils.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName FrameBoostUtil
 * @Description TODO
 * @Author 方丈
 * @Date 2021/2/19 11:51
 * @Version 1.0.0
 **/
public class FrameBoostUtil {
    private static Logger logger = LoggerFactory.getLogger(FrameBoostUtil.class);
    static String osName;
    static {
        osName = System.getProperty("os.name");
        logger.info("----系统名称：{}-----",osName);
    }

    public static boolean isLinux() {
        return osName.toLowerCase().indexOf("linux") >= 0;
    }

    public static String fileMd5(File file){
        String md5Hex=null;
        if(isLinux()){
            return FileShellUtils.md5(file.getAbsolutePath());
        }else {
            try (FileInputStream fileInputStream = new FileInputStream(file);){
                md5Hex = DigestUtils.md5Hex(fileInputStream);
            }catch (Exception e){
                FrameworkUtils.throwExRet(e);
            }
        }
        return md5Hex;
    }

    public static Long getUserNoIfNull(){
        String userNo= FrameworkContextDataHolder.getContextUserNo();
        return StringUtils.isBlank(userNo)? 0L:Long.parseLong(userNo);
    }

    public static String getUserNameIfNull(){
        String userName= FrameworkContextDataHolder.getContextUserName();
        return StringUtils.isBlank(userName)? "0":userName;
    }

    public static Object getFromTokenExtJson(String key){
        String tokenExtJson = FrameworkUtils.getTokenExtJson();
        Map extJson = ObjectMapperUtils.readToObject(tokenExtJson, Map.class,new ObjectMapper());
        if(JudgeUtils.isNull(extJson)){
            return null;
        }
        return extJson.get(key);
    }

    public static Integer generateRandInt(int min,int max){
        Random random = new Random();
        return random.nextInt(max)%(max-min+1) + min;
    }


    public static boolean lockTask(String taskName, StringRedisTemplate stringRedisTemplate){
        String s = stringRedisTemplate.opsForValue().get(taskName);
        if(JudgeUtils.isNotBlank(s)){
            return false;
        }
        stringRedisTemplate.opsForValue().set(taskName,taskName.concat("-running"),30, TimeUnit.DAYS);
        return true;
    }

    public static boolean unlockTask(String taskName, StringRedisTemplate stringRedisTemplate){
        stringRedisTemplate.delete(taskName);
        return true;
    }

    public static <T> void shieldSensitiveFields(T obj){
        Class clazz = obj.getClass();
        List<Field> fields = Arrays.asList(clazz.getDeclaredFields());

        fields.stream().forEach(
                f->{
                    Object fieldValue = ReflectionUtils.getFieldValue(obj, f.getName());
                    if(fieldValue !=null && fieldValue instanceof String){
                        String val = (String) fieldValue;
                        if(JudgeUtils.isNotBlank(val) && val.indexOf("**")>0){
                            ReflectionUtils.setFieldValue(obj,f.getName(),null);
                        }
                    }
                }
        );
    }
}
